package com.eastcom.notice;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.apache.log4j.Logger;

public class SingleSocketHandler
  implements Runnable
{
  private static int refreshClentTime;
  private Logger log;
  private ServerSocket server;
  private List<NoticeMessage> aliveSocket = Collections.synchronizedList(new ArrayList());

  public SingleSocketHandler(ServerSocket server) {
    this.server = server;
    MessageFactory.init(this.aliveSocket);
  }

  public void run() {
    new Thread(new Runnable()
    {
      public void run() {
        while (true) {
          try {
            Thread.sleep(SingleSocketHandler.refreshClentTime);
          }
          catch (InterruptedException e) {
            e.printStackTrace();
          }
          SingleSocketHandler.this.log.info("scan Notice[socket] client:");
          Iterator it = SingleSocketHandler.this.aliveSocket.iterator();
          while (it.hasNext()) {
            NoticeMessage so = (NoticeMessage)it.next();
            if (!(so.isConnect()))
              it.remove();
          }
          SingleSocketHandler.this.log.info("socket Client num : " + SingleSocketHandler.this.aliveSocket.size());
        }
      }
    }).start();
    this.log.info("waiting  Clients ...............");
    while (true)
      try {
        Socket socket = this.server.accept();
        this.aliveSocket.add(new NoticeMessage(socket, this.aliveSocket));
        this.log.info("Socket Client: [   " + socket.getLocalAddress() + "   ] success!!");
      }
      catch (IOException e) {
        e.printStackTrace();
      }
  }
}